package com.zhou;

import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFComment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws IOException {
        new File("txt").mkdirs();

        File inDir = new File("word");
        if(inDir.exists() == false){
            System.out.println("word路径不存在");
            return;
        }

        List<File> files = readDocxFiles();
        System.out.println("docx文件数：" + files.size());
        for (int i = 0; i < files.size(); i++) {
            System.out.println(String.format("%d / %d", i+1, files.size()));
            File file = files.get(i);
            saveTxt(file, "txt/" + file.getName().replace(".docx", ".txt"));
        }

        files = readDocFiles();
        System.out.println("doc文件数：" + files.size());
        for (int i = 0; i < files.size(); i++) {
            System.out.println(String.format("%d / %d", i+1, files.size()));
            File file = files.get(i);
            saveTxt(file, "txt/" + file.getName().replace(".doc", ".txt"));
        }

        System.out.println("完成");
    }

    public static void saveTxt(File file, String name) throws IOException {
        StringBuilder content = new StringBuilder("");

        XWPFDocument document = new XWPFDocument(new FileInputStream(file));
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            content.append(paragraph.getText() + "\n\r");
        }

        FileUtils.writeStringToFile(new File(name), content.toString(), "gbk");
    }

    public static List<File> readDocxFiles(){
        File inDir = new File("word");
        File[] files = inDir.listFiles((d, n) -> n.endsWith(".docx"));
        return Arrays.asList(files);
    }

    public static List<File> readDocFiles(){
        File inDir = new File("word");
        File[] files = inDir.listFiles((d, n) -> n.endsWith(".doc"));
        return Arrays.asList(files);
    }
}
